# !/bin/bash

### BEGIN INIT INFO
# Provides:          watchDog
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: start watchDog
# Description:       start watchDog
### END INIT INFO

#改buff, 还需要改vision/armor构造函数里面的SetModel为 kWINDBUFF, 如SetModel(game::Model::kWINDBUFF);
#以后换service配置自启动

sec=1
cnt=0
PROC_NAME=buff # auto-aim buff 进程名字，取决于你自己make后的名称，也可以在终端输入top来查找
APP_FOLDER=buff  # auto_aim, buff
Thread=`ps -ef | grep $PROC_NAME | grep -v "grep"` # 判断用到，具体用法自行百度

exit(0) #测试代码

echo "dji" | sudo -S sudo chmod +777 /dev/ttyTHS2 # 用自动输入密码并开启ttyusb权限

{ # try
	cd /home/dji/Desktop/define9/beta-define9-rmai/build/src/app/$APP_FOLDER
	echo "dji" | sudo -S sudo chmod +x /home/dji/Desktop/define9/beta-define9-rmai/build/src/app/$APP_FOLDER/$PROC_NAME
	echo "dji" | sudo -S sudo -u dji /home/dji/Desktop/define9/beta-define9-rmai/build/src/app/$APP_FOLDER/$PROC_NAME # 运行
} || { # catch
    # save log for exception
	echo "dji" | sudo -S sudo -u dji cmake --no-warn-unused-cli -DCMAKE_EXPORT_COMPILE_COMMANDS:BOOL=TRUE -DCMAKE_BUILD_TYPE:STRING=Release -DCMAKE_C_COMPILER:FILEPATH=/usr/bin/gcc-9 -DCMAKE_CXX_COMPILER:FILEPATH=/usr/bin/g++-9 -H/home/dji/Desktop/define9/beta-define9-rmai -B/home/dji/Desktop/define9/beta-define9-rmai/build -G "Unix Makefiles"
	echo "dji" | sudo -S sudo -u dji cmake --build /home/dji/Desktop/define9/beta-define9-rmai/build --config Release --target $PROC_NAME -j 8
}

while test 1  # 循环，记得大括号里面的1两边都要空格
do
	count=`ps -ef | grep $PROC_NAME | grep -v "grep" | wc -l` # 判定进程运行否，是则继续，否则重新启动
	echo "Thread count: $count"
	if test $count -gt 1 ;then  # -gt 大于1情况下 进程没被杀害
		echo "The $PROC_NAME is still alive!"
		sleep $sec
	else  # 进程被杀害
		echo "Starting $PROC_NAME"
		cd /home/dji/Desktop/define9/beta-define9-rmai/build/src/app/$APP_FOLDER
		echo "dji" | sudo -S sudo chmod +777 /dev/ttyTHS2 # dji是我minipc上的密码
		echo "dji" | sudo -S sudo -u dji /home/dji/Desktop/define9/beta-define9-rmai/build/src/app/$APP_FOLDER/$PROC_NAME
		echo "$PROC_NAME has started!"
		sleep $sec
	fi
done
